<template>
  <van-row class="confirmOrder">
    <van-nav-bar fixed :z-index="100" title="订单确认" left-arrow @click-left="onClickLeft" />
    <div class="ordercontent">
      <div class="orderAddress">
        <van-cell-group>
          <van-cell icon="location-o" :label="confirmedAddress.address" is-link @click="confirmAddress(confirmedAddress)">
            <template slot="title">
              <span class="custom-title">{{confirmedAddress.name}}</span>
              <span class="custom-title">{{confirmedAddress.tel}}</span>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      <div class="orderSpec">
        <div v-for='(boxItem,index) in orderList' :key="boxItem.id">
          <div class="box-item-title">{{boxItem.comName}}</div>
          <div class="order-item" v-for="item in boxItem.omsCartItems" :key="item.id">
            <van-card :num="item.quantity || item.num" :price="item.price" :desc="item.productName"
              :title="item.productSubTitle" :thumb="item.productPic">
              <div slot="tags" v-if="$route.query.type == 'dir' ">
                <van-tag plain type="danger" v-for="item in JSON.parse(item.productAttr)" :key="item.key">
                  {{item.key}}:{{item.value}}</van-tag>
              </div>
              <div slot="tags" v-else>
                <van-tag plain type="danger" v-for="item in JSON.parse(item.productAttr)" :key="item.key">
                  {{item.key}}:{{item.value}}</van-tag>
              </div>
            </van-card>
          </div>
          <van-cell-group>
              <van-field v-model="messageList[index]" rows="1" autosize label="留言" type="textarea" placeholder="请输入留言" />
          </van-cell-group>
          <van-cell title="商品金额" :value="`￥${boxItem.totalAmount.toFixed(2)}`" />
          <van-cell title="运费" :value="`${boxItem.totalFare == 0?'包邮':'￥'+boxItem.totalFare.toFixed(2)}`" />
          <van-cell title="实付款" :value="`￥${boxItem.payAmount.toFixed(2)}`" class='pay-amount'/>

        </div>
        <van-cell class="Integral" v-if="totalIntegral > 0 && userInfo.integration.availableScore > 0">
          <van-checkbox v-model="checkedIntegral" checked-color="#FE472D" icon-size="20px">
              <span>使用积分</span>
              <span class="deduction">￥-<b ref='integrmb'>{{integRmb}}</b></span>
          </van-checkbox>
          <div class="hint">
            <span>(您有{{userInfo.integration.availableScore}}个，</span>
            可用
            <span ref='integ'>{{userInfo.integration.availableScore > totalIntegral? totalIntegral: userInfo.integration.availableScore}}</span>
            个)
          </div>
        </van-cell>

      </div>
    </div>
    <van-submit-bar :price="totalPrice*100" button-text="去支付" @submit="toSumbitOrder" />
    <store-pay-dialog @getPayPassword="getPayPassword" @closeDialog="closeDialog" @toPay="toPay" :show="showPayDialog">
    </store-pay-dialog>
  </van-row>
</template>
<script>
  import Vue from 'vue'
  import { mapState, mapActions } from 'vuex'
  import { wxpay } from '@/utils/wxpay'
  import storePayDialog from '@/components/store-pay-dialog'
  import { getClient } from '@/utils/util'
  import {
    Checkbox,
    NavBar,
    Card,
    Button,
    Tag,
    Row,
    Toast,
    Icon,
    Cell,
    CellGroup,
    Tabbar,
    TabbarItem,
    Dialog,
    SubmitBar, Field
  } from 'vant'
  Vue.use(NavBar)
    .use(Card)
    .use(Button)
    .use(Tag)
    .use(Row)
    .use(Toast)
    .use(Icon)
    .use(Cell)
    .use(CellGroup)
    .use(Tabbar)
    .use(TabbarItem)
    .use(Dialog)
    .use(SubmitBar)
    .use(Field)
    .use(Checkbox)
  export default {
    name: 'confirmOrder',
    components: {
      storePayDialog
    },
    data() {
      return {
        checkedIntegral: false, // 是否使用积分
        showPayDialog: false, //支付弹框默认隐藏
        payType: '', //获取支付方式
        methodType: '', // 支付客户端
        showAddress: false, //显示地址列表
        confirmedAddress: {
          name: '',
          tel: '',
          address: ''
        }, //默认显示地址
        payParamsObj: {}, //传给自己后台支付接口的数据
        channel: null,
        aliChannel: null,
        wxChannel: null,
        isBalanceEnough: false, // 余额是否足购支付
        payPassword: '', //支付密码
        isCreatOrder: false,
        orderList: [], // 确认定单列表
        messageList:[],
        configValue: 0.1 // 积分兑换比例默认1/10
      }
    },
    computed: {
      ...mapState({
        confirmOrderList: state => state.order.confirmOrderList,
        clientId: state => state.sys.clientId,
        addressInfo: state => state.address.addressInfo,
        userInfo: state => state.user.userInfo
      }),
      /* 合计 */
      totalPrice() {
        // 使用积分抵扣
        if (this.checkedIntegral) {
          return this.orderList.reduce((pre, cur) => {
            return pre + cur.payAmount
          }, 0) - parseFloat(this.$refs.integrmb.innerHTML)
        } else {
          return this.orderList.reduce((pre, cur) => {
            return pre + cur.payAmount
          }, 0)
        }
      },
      /* 可使用积分 */
      totalIntegral() {
        return  this.orderList.reduce((pre, cur) => {
          return pre + cur.totalIntegral
        }, 0)
      },
      /* 积分抵扣金额 */
      integRmb() {
        if (this.userInfo.integration.availableScore > this.totalIntegral) {
          return (this.totalIntegral * this.configValue).toFixed(2)
        } else {
          return (this.userInfo.integration.availableScore * this.configValue).toFixed(2)
        }
      }  
},
    created() {
      this.getAddressList() // 获取地址列表
      this.initAddress() // 获取用户的收货地址
      this.getUserInfo()
      this.integralAmount()
    },
    mounted() {
      this.onPlusReady(() => {
        this.getPayChannel()
      })
      this.getConfirmOrder() // 获取拆单信息
    },
    beforeDestroy() {
      // this.reInitAddressInfo()
    },
    watch: {
      addressInfo() {
        this.initAddress()
      }
    },
    methods: {
      ...mapActions('cart',['getCartList']),
      ...mapActions('user', ['getUserInfo']),
      ...mapActions('address', ['getAddressList', 'reInitAddressInfo']),

      /******** 获取积分兑换比例配置 ********/
      integralAmount() {
        this.$http.post('/config/configIntegral')
          .then((res)=> {
            this.configValue = res.info
          })
      },

      /******** 返回点击事件 ********/
      onClickLeft() {
        this.$router.go(-1)
      },

      /******** 获取确认定单列表 ********/
      getConfirmOrder() {
        const { confirmOrderList } = this;
        let data = { type: this.$route.query.type };
        // 从商品详情进入
        if (this.$route.query.type == 'dir') {
          data.skuIds = [confirmOrderList[0].id]
          data.quantity = confirmOrderList[0].quantity;
          data.productAttr = confirmOrderList[0].productAttr;
        } else {
          // 从购物车进入
          data.skuIds = confirmOrderList.map(item => {
            return item.productSkuId
          })
        }

        this.$http
          .post('/order/confirmOrder', data)
          .then(data => {
            this.orderList = data.info;
          })
          .catch(error => {
            console.log(error)
          })
      },
      /******** 点击打开支付弹框事件 ********/
      toShowPay() {
        this.$store.dispatch('payChannel/getPayChannel').then(() => {
          this.showPayDialog = true
          this.isBalanceEnough =
            this.userInfo.amsAccount.balance >= this.totalPrice
        })
      },
      /******** 获取用户的收货地址 ********/
      initAddress() {
        const { addressInfo } = this
        if (!addressInfo) {
          Toast.fail('请先添加地址')
          return
        }
        this.$nextTick(() => {
          this.confirmedAddress.name = addressInfo.name || '请先选择地址'
          this.confirmedAddress.tel = addressInfo.tel || ''
          this.confirmedAddress.id = addressInfo.id || ''
          if (addressInfo.province) {
            const detaliaddress = addressInfo.addressDetail || addressInfo.address
            this.confirmedAddress.address = `${addressInfo.province}${
              addressInfo.city
              }${addressInfo.county}${detaliaddress}`
          } else {
            this.confirmedAddress.address = ''
          }
        })
      },
      /******** 去支付 创建订单 ********/
      toSumbitOrder() {
        if (!this.confirmedAddress.address) {
          Toast.fail('请选择地址')
          return
        }
        const { confirmOrderList } = this
        let temSkuids = []
        if (this.$route.query.type == 'dir') {
          temSkuids = [confirmOrderList[0].id]
        } else {
          temSkuids = confirmOrderList.map(item => {
            return item.productSkuId
          })
        }
        let notes = [];
        for(let i =0;i<this.orderList.length;i++){
          if (this.messageList[i]) {
            notes.push({
              supId: this.orderList[i].id, note: this.messageList[i]
            })
          }
        }
        let params = {
          skuIds: temSkuids,
          addressId: this.addressInfo.id,
          type: this.$route.query.type,
          sourceType: this.clientId,
          notes: notes
        }
        // 使用积分抵扣
        if (this.checkedIntegral) {
          let integralCount = parseFloat(this.$refs.integ.innerHTML)
          params = {
            ...params,
            integralCount
          }
        }
        // 从商品界面点击购买
        if (this.$route.query.type == 'dir') {
          params = {
            ...params,
            quantity: confirmOrderList[0].quantity,
            productAttr: confirmOrderList[0].productAttr,
          }
          if (this.$route.query.recommenderId) {
            params = {
              ...params,
              recommenderId: this.$route.query.recommenderId
            }
          }
        }
        if (!this.isCreatOrder) {
          this.$http
            .post('/order/create', params)
            .then(data => {
              this.payParamsObj = {
                orderIds: data.info.orderIds.split(',')
              }
              this.toShowPay()
              this.getCartList() // 创建订单时，刷新购物车数量
            })
            .catch(error => {
              Toast.fail(error.message)
            })
        } else {
          this.toShowPay()
        }
      },

      /*************支付弹框事件群start******/
      /***********隐藏弹框*********/
      closeDialog() {
        let path = this.$route.path
        if (path != '/order?tabId=0') {
          this.$router.push('/order?tabId=0')
        }
      },
      /***********获取支付密码*********/
      getPayPassword(pw) {
        this.payParamsObj.password = pw
      },
      /* 去支付 */
      toPay(method, type, callback, hideRadio) {
        // method => 支付通道(WXPAY、ALIPAY、BALANCE), type => 支付方式(APP、H5)
        this.payType = method
        this.payParamsObj.methodType = type
        this.payParamsObj.clientId = getClient()
        if (this.payType == '' || !this.payType) {
          Toast.fail('请选择您需要的支付方式')
          return
        }
        if (this.payType == 'WXPAY') {
          this.payParamsObj.payType = 'WXPAY'
          this.channel = this.wxChannel
        } else if (this.payType == 'ALIPAY') {
          this.payParamsObj.payType = 'ALIPAY'
          this.channel = this.aliChannel
        } else if (this.payType == 'PCREDIT') {
          this.payParamsObj.payType = 'PCREDIT'
          this.channel = this.aliChannel
        } else {
          this.payParamsObj.payType = 'BALANCE'
          if (!this.isBalanceEnough) {
            Toast.fail('余额不足以支付该产品')
            if (typeof callback == 'function') {
              callback();
              hideRadio();
            }
            this.$router.push({
              name: 'order',
              query: {
                tabId: 0
              }
            })
            return
          }
        }
        this.$http.post('/trade/pay', this.payParamsObj).then(data => {
          if (this.payType == 'BALANCE') {
            this.showPayDialog = false
            if (typeof callback == 'function') {
              callback()
              hideRadio()
            }
            Toast.success('支付成功')
            this.$router.push({
              name: 'order',
              query: {
                tabId: 0
              }
            })
            return
          }

          // 支付宝(测试通过)
          if (this.payType == 'ALIPAY' || this.payType == 'PCREDIT') {
            if (this.clientId == 1) {
              let temPrams = data.info.info
              plus.payment.request(
                this.channel,
                temPrams,
                () => {
                  plus.nativeUI.alert('支付成功！', function() {
                    if (typeof callback == 'function') {
                      callback()
                      hideRadio()
                    }
                    this.$router.push({
                      name: 'order',
                      query: {
                        tabId: 0
                      }
                    })
                  })
                },
                error => {
                  plus.nativeUI.alert('支付失败：' + error.code)
                }
              )
            }
          }

          if (this.payType == 'WXPAY') {
            // App
            if (this.clientId == 1) {
              // App内使用H5方式支付
              if (type == 'H5') {
                // 接口返回来的微信H5支付的链接地址
                let payUrl = data.info.mweb_url;
                let self = plus.webview.currentWebview();
                let payView = plus.webview.create(payUrl, 'pay-url', {
                  top: '1000px', bottom: '1000px',
                  additionalHttpHeaders: { referer: process.env.VUE_APP_HOST }
                });
                self.append(payView);
              } else if(type == 'APP') {
                // App内使用原生方式
                let temPrams = data.info
                temPrams.timestamp = parseInt(data.info.timestamp)
                
                plus.payment.request(
                  this.channel,
                  temPrams,
                  () => {
                    plus.nativeUI.alert('支付成功！', function() {
                      if (typeof callback == 'function') {
                        callback()
                        hideRadio()
                      }
                      this.$router.push({
                        name: 'order',
                        query: {
                          tabId: 0
                        }
                      })
                    })
                  },
                  error => {
                    plus.nativeUI.alert('支付失败：' + error.code)
                  }
                )
              }
              return
            }
            // 网页 wap
            if (this.clientId == 2) {
              // 接口返回来的微信H5支付的链接地址
              let payUrl = data.info.mweb_url;
              window.location.href = payUrl
              return
            }
            // wx 内置浏览器
            if (this.clientId == 3) {
              wxpay(data.info, payResult => {
                if (payResult.err_msg == 'get_brand_wcpay_request:ok') {
                  Toast.success('支付成功')
                  this.$router.push({
                    name: 'order',
                    query: {
                      tabId: 0
                    }
                  })
                } else {
                  Toast.fail('支付失败')
                  this.$router.push({
                    name: 'order',
                    query: {
                      tabId: 0
                    }
                  })
                }
              })
              return
            }
          }
          if (typeof callback == 'function') {
            hideRadio();
          }
        })
          .catch(err => {
            if (this.payType == 'BALANCE' && err.errcode == 127) {
              Dialog.confirm({
                title: '提示',
                message: '密码输入错误',
                confirmButtonText: '重新输入'
              }).then(() => {
               
              }).catch(() => {
                if (typeof callback == 'function') {
                  callback();
                  hideRadio();
                  this.$router.push({
                    name: 'order',
                    query: {
                      tabId: 0
                    }
                  })
                }
              });
            } else if (this.payType == 'BALANCE') {
              if (typeof callback == 'function') {
                callback();
                hideRadio();
              }
              this.$router.push({
                name: 'order',
                query: {
                  tabId: 0
                }
              })
            }
            else {
              Toast.fail(err.message);
              this.$router.push({
                name: 'order',
                query: {
                  tabId: 0
                }
              })
              if (typeof callback == 'function') {
                hideRadio();
              }
            }
            this.showPayDialog = false
          })
      },
      /***********点击支付按钮事件并获取支付方式*********/


      //       /* 黄亮
      //   if (this.clientId == 2) {
      //         //wap
      //         window.location.href = data.info.mweb_url
      //         return
      //       }
      //       if (this.clientId == 3) {
      //         //wx
      //         this.wxpay(data.info, payResult => {
      //           if (payResult.err_msg == 'get_brand_wcpay_request:ok') {
      //             //执行
      //             Toast.success('支付成功')
      //             this.$router.push('/order')
      //           } else {
      //             Toast.fail('支付失败')
      //             this.$router.push('/order')
      //           }
      //         })
      //         return
      //       } 
      //       if (this.clientId == 1) {
      //         // app
      //         let temPrams = data.info
      //         temPrams.timestamp = parseInt(data.info.timestamp)
      //         plus.payment.request(
      //           this.channel,
      //           temPrams,
      //           res => {
      //             this.$http
      //               .post('trade/tradeDetail', { tradeNo: temPrams.tradeNo })
      //               .then(data => {
      //                 plus.nativeUI.alert('支付成功！', function() {
      //                   this.$router.push('/order')
      //                 })
      //               })
      //           },
      //           error => {
      //             plus.nativeUI.alert('支付失败：' + error.code)
      //           }
      //         )
      //       }
      //   */
      //     }
      //   })
      // },
      /*************支付弹框事件群end******/

      /*************取消订单******/
      cancelOrder() {
        console.log('cancel')
      },

      /********打开地址列表**** */
      confirmAddress(confirmedAddress) {
        this.$router.push({
          path: '/address',
          query: {
            chosenAddressId: confirmedAddress.id,
            type: 'select'
          }
        })
      },

      /*******调用5+支付功能********** */
      getPayChannel() {
        // 获取支付通道
        plus.payment.getChannels(
          channels => {
            for (var i = 0; i < channels.length; i++) {
              if (channels[i].id == 'alipay') {
                this.aliChannel = channels[i]
              } else if (channels[i].id == 'wxpay') {
                this.wxChannel = channels[i]
              }
            }
          },
          function (e) {
            plus.nativeUI.alert('获取支付通道失败：' + e.message)
          }
        )
      }
    }
  }
</Script>
<style lang="scss" scoped>
  .confirmOrder {
    padding-top: 46px;
    .box-item-title{
      padding: 10px 16px;
      background: white;
      font-size: 18px;
      margin-top:10px;
    }
    .ordercontent {
      padding-bottom: 50px;
      padding-top: 20px;
    }

    .orderAddress {
      margin-top: 10px;

      .van-cell__left-icon {
        height: 45px;
        font-size: 40px;
        line-height: 45px;
        width: 45px;
        background: $red;
        border-radius: 50%;
        color: #fff;
        text-align: center;
      }

      .van-cell__right-icon {
        height: 45px;
        line-height: 45px;
      }

      .custom-title {
        margin-right: 10px;

        &:nth-child(2) {
          color: $gray-deep;
        }
      }
    }

    .orderSpec {
      margin-top: 10px;

      /* .order-item {
        margin-bottom: 10px;
      } */

      .van-card {
        background: #fff;
      }

      .van-cell {
        font-size: 16px;

        /* &:nth-child(3) {
          .van-cell__value {
            color: $red;
          }
        } */
      }
      .pay-amount{
        .van-cell__value {
            color: $red;
          }
      }
      .van-checkbox{
        -webkit-justify-content: flex-end;
        justify-content: flex-end;
      }
      /deep/ .van-checkbox__icon .van-icon{
        width: 20px;
        height: 20px;
      }
      .Integral{
        font-size: 12px;
        margin: 10px 0;
        .deduction{
          font-size: 18px;
          padding-left: 20px;
        }
        .hint{
          text-align: right;
        }
      }
    }

    .van-tabbar {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
      .van-button {
        border-radius: 11px;

        margin: 0 10px;
      }
    }
  }
</style>